import Icon from 'components/Icon';
import React, {MouseEventHandler} from 'react';
import {getToday, setDateFrom} from 'lib/dayUtils';
import {CalendarWrapper} from './CalendarSection/CalendarWrapper';
import {useRecords} from 'hooks/useRecords';
import {getFullDate} from './CalendarSection/getFullDate';
import {getDaysList} from './CalendarSection/getDaysList';
import {DateInfo} from './CalendarSection/DateInfo';
import {DirType} from '../../../hooks/useCalendarDate';

type Props = {
  accountsDate: string;
  onClickMonth: (direction: DirType) => void
  onClickDate: (value: string) => void
}
const CalendarSection: React.FC<Props> = (props) => {
  const {accountsDate, onClickMonth, onClickDate} = props;
  const {calculateMonthTotal} = useRecords()
  const {monthRecords} = calculateMonthTotal(accountsDate)

  const getDateInfo = (itemContent: number | string) => {
    const createdAt = getFullDate(accountsDate, itemContent);
    if (createdAt in monthRecords) {
      const {dateCost, dateIncome} = monthRecords[createdAt];
      return <DateInfo dateCost={Math.ceil(dateCost)} dateIncome={Math.ceil(dateIncome)}/>;
    }
  };

  const onClickBox: MouseEventHandler<HTMLOListElement> = (e) => {
    let target = e.target as HTMLElement;
    while (!target.matches('li')) {
      if (target === e.currentTarget) {
        break;
      }
      target = target.parentNode ? (target.parentNode as HTMLElement) : e.currentTarget;
    }
    if (target !== null && target.matches('li')) {
      if(!target.firstChild || !target.firstChild.nodeValue) return
      const newSelectedDate = setDateFrom(accountsDate, parseInt(target.firstChild.nodeValue));
      onClickDate(newSelectedDate);
    }
  };

  const yearMonth = accountsDate.replaceAll('-', '.').substring(0, 7);
  const daysList = getDaysList(accountsDate);
  return (
    <CalendarWrapper>
      <header>
        <div className="monthSelector">
          <Icon name="left" onClick={() => {onClickMonth('left');}}/>
          <span>{yearMonth}</span>
          <Icon name="right" onClick={() => {onClickMonth('right');}}/>
        </div>
        <button className="today" onClick={() => {onClickDate(getToday());}}>今天</button>
      </header>
      <ol className="week">
        <li>一</li>
        <li>二</li>
        <li>三</li>
        <li>四</li>
        <li>五</li>
        <li>六</li>
        <li>七</li>
      </ol>
      <ol className="days clearfix"
          onClick={onClickBox}>
        {daysList.map((item, index) => (
          <li key={index} className={getFullDate(accountsDate, item) === accountsDate ? 'selected' : undefined}>
            {item}
            {getDateInfo(item)}
          </li>
        ))}
      </ol>
    </CalendarWrapper>
  );
};

export {CalendarSection};